const async = require('async');
const mysql = require('../../utils/db').mysql;
exports.page = function(req, res, next){
    const id = req.query.id;
    const userInfo = req.session.userInfo;
    if(userInfo.userType != 1){
        res.statusCode = 404;
        res.send('404');
        return;
    }
    if(!id){
        res.status = 404;
        res.send('404');
        return;
    }
    req.session.touch();
    async.auto({
        info: function(callback){
            const queryStr = 'SELECT * FROM adminuser WHERE id=' + id;
            mysql.getConnection(function(err, conn) {
                conn.query(queryStr, function (err, result) {
                    if (err) {
                        // 错误处理
                    }
                    if (result.length > 0) {
                        callback(null, result[0]);
                    } else {
                        callback(null, {});
                    }
                    mysql.releaseConnection(conn);
                })
            })
        }
    }, function(err, results){
        res.render('admin/updateUser', {
            userInfo: userInfo,
            results: results,
            channel: {
                type: 'manage-user',
                index: 1
            }
        });
    })
}
exports.updateUser = function(req, res, next){
    const id = req.body.id;
    const data = {
        username: req.body.username,
        usertype: req.body.usertype,
        newsAuthority: req.body.newsAuthority || 2,
        flowerAuthority: req.body.flowerAuthority || 2
    };
    const userInfo = req.session.userInfo;
    if(userInfo.userType != 1){
        res.send({
            code: 400,
            msg: '没有权限'
        })
        return;
    }
    const queryStr = 'UPDATE adminuser SET username=?,usertype=?,newsAuthority=?,flowerAuthority=? WHERE id="' + id + '"';
    const valueArr = [data.username, data.usertype, data.newsAuthority, data.flowerAuthority];
    mysql.getConnection(function(err, conn) {
        conn.query(queryStr, valueArr, function (err, result) {
            if (err) {
                res.send({
                    code: 400,
                    msg: '更新失败'
                })
            } else {
                res.send({
                    code: 200,
                    msg: '更新成功'
                })
            }
            mysql.releaseConnection(conn);
        })
    })
}